/**
 * Created by jianglinjie on Wed Aug 23 2017
 * @flow
 */
'use strict';
/* eslint-disable no-unused-vars*/
//加载所有模型
import * as Models from './models';

import config from '../config';
import mongoose from 'mongoose';
import { logger } from '../utils/LoggerUtils';

const dbConfig = config.db;
const uri = `mongodb://${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`;
const options = {
  useMongoClient: true,
  autoReconnect: true,
  reconnectTries: Number.MAX_VALUE, 
  reconnectInterval: 500, 
  poolSize: 10,
};
const RETRY_TIME = 2000;

mongoose.connection.on('connecting', () => {
  logger.info('db connecting');     
});

mongoose.connection.on('connected', () => {
  logger.info('db connected');        
});

mongoose.connection.on('open', () => {
  logger.info('db open');     
});

mongoose.connection.on('disconnecting', () => {
  logger.info('db disconnecting');        
});

mongoose.connection.on('close', () => {
  logger.info('db close');     
});

mongoose.connection.on('reconnected', () => {
  logger.info('db reconnected');     
});

mongoose.connection.on('error', (error) => {
  logger.error('db error event ', error);    
});

async function connectWithRetry() {
  logger.info('db begin connect uri: ', uri);        
  try {
    //内部调用mongoose.connection(默认连接)的openUri
    await mongoose.connect(uri, options);
    logger.error('db connect succeed %s', uri);      
  } catch (error) {
    logger.error('db connect error ', error);  
    setTimeout(connectWithRetry, RETRY_TIME);
  }
}

connectWithRetry();

module.exports = mongoose.connection;

